"""
Map manipulation views
"""

from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from django.views.decorators.cache import cache_page

from map.models import Service

from urllib2 import urlopen

@login_required
def show(request, service, x, y, z):
  """Show map from service 'service' at coordinates (x, y) and zoom level z"""
  return render_to_response('map/show.html', {'service': service, 'x': x, 'y': y, 'z': z})

@login_required
@cache_page(60 * 60) # Cache each map request for one hour
def get(request, service, xSize, ySize, x, y, z):
  """Get image file for 'service' at coordinates (x, y) and zoom level z with dimensions (xSize, ySize)"""
  s = get_object_or_404(Service, name=service)
  
  img = urlopen(s.url%{
    'xSize': xSize, 'ySize': ySize, 'x': x, 'y': y, 'z': z, 'key': s.key
      }).read()
  
  response = HttpResponse(mimetype='image/gif')
  
  response.write(img)
  
  return response
